<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>父组件访问子组件暴露的数据</title>
</head>
<body>
<div id="app">
    <cpn1 ref="comp1"></cpn1>
    <cpn2 ref="comp2"></cpn2>

    <button v-on:click="btnClicked">获取</button>
</div>

<template id="cpn">
    <h1>我是自定义组件</h1>
</template>

<script type="module">
    import {createApp, ref, defineComponent} from "../../../js/vue.esm-browser.js";

    let component1 = defineComponent(
        {
            template: "#cpn",
            setup(props, context) {
                let info = ref("Hello, Vue! ")

                function showMessage() {
                    console.log("function showMessage from cpn1");
                }

                // 组件主动暴漏变量和函数
                context.expose(
                    {
                        info,
                        showMessage,
                    }
                )
                return {
                    info, showMessage,
                };
            }
        }
    );

    let component2 = defineComponent(
        {
            template: "#cpn",
            // 将 第二个参数 context 进行解构，

            setup(props, {expose}) {
                // console.log(context);
                let info = ref("Hello, World! ")
                let message = ref("abc")

                function showMessage() {
                    console.log("function showMessage from cpn2");
                }

                // 组件主动暴漏变量和函数
                expose(
                    {
                        info,
                        showMessage,
                    }
                )
                return {
                    info, showMessage,message,
                };
            }
        }
    );

    let app = createApp(
        {
            setup() {
                let comp1 = ref(null)
                console.log(comp1.value);

                let comp2 = ref(null)
                console.log(comp2.value);

                function btnClicked() {

                    console.log(comp1.value);
                    console.log(comp1.value.info);
                    comp1.value.showMessage()

                    console.log(comp2.value);
                    console.log(comp2.value.info);
                    comp2.value.showMessage()
                    // 子组件中未暴露的变量无法访问
                    console.log(comp2.value.message);
                }

                return {
                    comp1, btnClicked, comp2,
                }
            }
        }
    );

    app.component("cpn1", component1)
    app.component("cpn2", component2)

    app.mount("#app")
</script>
</body>
</html>